package com.juyu.miliao.common.redis;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.common.domain.dto.UserCallTimesDTO;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户通话时长key
 * @author xuanqicheng
 */
public class UserCallTimeRedis {

    private static final String  USER_CALL_TIMES_HASH_KEY = "USER_CALL_TIMES_HASH:";
    private static final String USER_LAST_CALL_TIMES_HASH_KEY = "USER_LAST_CALL_TIMES_HASH";
    private StringRedisTemplate stringRedisTemplate;

    public UserCallTimeRedis(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void setUserCallTimes(long userId,int minute){
        String key = USER_CALL_TIMES_HASH_KEY+ LocalDate.now().toString();
        stringRedisTemplate.opsForHash().increment(key,Long.toString(userId),minute);
        stringRedisTemplate.expire(key,31, TimeUnit.DAYS);
    }

    public List<UserCallTimesDTO> getUserCallTimes(LocalDate localDate){
        String key = USER_CALL_TIMES_HASH_KEY+localDate.toString();
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(key);
        List<UserCallTimesDTO> list = new ArrayList<>();
        for(Map.Entry<Object,Object> entry:map.entrySet()){
            UserCallTimesDTO userCallTimesDTO = new UserCallTimesDTO();
            userCallTimesDTO.setUserId(Long.parseLong(entry.getKey()+""));
            userCallTimesDTO.setMinutes(Integer.parseInt(entry.getValue()+""));
            list.add(userCallTimesDTO);
        }
        return list;
    }

    public void setUserLastCallTime(long userId){
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime=LocalDateTime.now(ZoneOffset.of("+8"));
        String time = df.format(localDateTime);
        String key = USER_LAST_CALL_TIMES_HASH_KEY;
        stringRedisTemplate.opsForHash().put(key,Long.toString(userId),time);
    }

    public String getUserLastCallTimeByUserId(long userId){
        String key = USER_LAST_CALL_TIMES_HASH_KEY;
        Object target= stringRedisTemplate.opsForHash().get(key,Long.toString(userId));
        if(target!=null){
            return (String) target;
        }else{
            return null;
        }
    }

}
